{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2840bdb2",
   "metadata": {},
   "source": [
    "# 百度AI开放平台-OCR（光学字符识别）\n",
    "## 通用文字识别\n",
    "### 接口描述\n",
    "在通用文字识别的基础上，提供更高精度的识别服务，支持更多语种识别（丹麦语、荷兰语、马来语、瑞典语、印尼语、波兰语、罗马尼亚语、土耳其语、希腊语、匈牙利语、泰语、越语、阿拉伯语、印地语及部分中国少数民族语言），并将字库从1w+扩展到2w+，能识别所有常用字和大部分生僻字。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b4f49a62",
   "metadata": {},
   "source": [
    "# 请求示例                              \n",
    "HTTP 方法：POST                                 \n",
    "请求URL： https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic\n",
    "请求参数                                      \n",
    "url参数-token                                       \n",
    "图片参数-图片文件                                     \n",
    "示例代码1："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "5c82705a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'error_code': 6, 'error_msg': 'No permission to access data'}\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用文字识别（高精度版）\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('shufa.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img}\n",
    "access_token = '24.5370c249eeacfa5def4efcbe860d468f.2592000.1652358051.282335-25869197'\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9dab6e22",
   "metadata": {},
   "outputs": [],
   "source": [
    "示例代码2：\n",
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\"\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('xihu.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':zhichao_AT,\n",
    "    'image':img,\n",
    "    'baike_num':5\n",
    "}\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "9e9f9722",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.7afa9f03c046f595f2c61f2333029849.315360000.1965126632.282335-25954563', 'expires_in': 2592000, 'session_key': '9mzdXU2Ajr5g4gAeNcGvVFaIG7bF5BEPmOA0kItUHIKx5yvA0iWF4UqhdMgKGY686JA9RESxd0X6TB//ka8oAB8adonmcA==', 'access_token': '24.f9de814de8230b35a30dbf045fd44274.2592000.1652358632.282335-25954563', 'scope': 'public vis-ocr_ocr brain_ocr_scope brain_ocr_general brain_ocr_general_basic vis-ocr_business_license brain_ocr_webimage brain_all_scope brain_ocr_idcard brain_ocr_driving_license brain_ocr_vehicle_license vis-ocr_plate_number brain_solution brain_ocr_plate_number brain_ocr_accurate brain_ocr_accurate_basic brain_ocr_receipt brain_ocr_business_license brain_solution_iocr brain_qrcode brain_ocr_handwriting brain_form brain_ocr_passport brain_ocr_vat_invoice brain_numbers brain_ocr_business_card brain_ocr_train_ticket brain_ocr_taxi_receipt vis-ocr_household_register vis-ocr_vis-classify_birth_certificate vis-ocr_台湾通行证 vis-ocr_港澳通行证 vis-ocr_机动车购车发票识别 vis-ocr_机动车检验合格证识别 vis-ocr_车辆vin码识别 vis-ocr_定额发票识别 vis-ocr_保单识别 vis-ocr_机打发票识别 vis-ocr_行程单识别 brain_ocr_vin brain_ocr_quota_invoice brain_ocr_birth_certificate brain_ocr_household_register brain_ocr_HK_Macau_pass brain_ocr_taiwan_pass brain_ocr_vehicle_invoice brain_ocr_vehicle_certificate brain_ocr_air_ticket brain_ocr_invoice brain_ocr_insurance_doc brain_formula brain_seal brain_ocr_facade brain_ocr_meter brain_doc_analysis brain_ocr_webimage_loc brain_ocr_medical_paper brain_ocr_doc_analysis_office brain_vat_invoice_verification brain_ocr_medical_detail brain_vehicle_registration_certificate brain_ocr_online_taxi_itinerary brain_ocr_multi_idcard brain_ocr_mixed_multi_vehicle brain_ocr_weigth_note brain_ocr_ multiple_invoice wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online', 'session_secret': '02fab35cdd9aa116bb98462571020b09'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?'\n",
    "payload = {\n",
    "    'grant_type':'client_credentials',\n",
    "    'client_id':'Zk0vqYYlnLUsAKrT0uvLKsab',\n",
    "    'client_secret':'fcrMEHuiIUkHp2tdXDaDnBjH5GX34gpI'\n",
    "}\n",
    "response = requests.get(host,params=payload)\n",
    "if response:\n",
    "    print(response.json())\n",
    "    access_token = response.json()['access_token']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "1438e1b1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.f9de814de8230b35a30dbf045fd44274.2592000.1652358632.282335-25954563'"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "access_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f3fab199",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 实践A-1\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dca9f836",
   "metadata": {},
   "source": [
    "* 网络图片文字识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "fe500d36",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': [{'words': '小丑竟是我自己'}], 'words_result_num': 1, 'log_id': 1513857201967578284}\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "网络图片文字识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/webimage\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('xiaochou.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img}\n",
    "access_token = '24.f9de814de8230b35a30dbf045fd44274.2592000.1652358632.282335-25954563'\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "677c4388",
   "metadata": {},
   "source": [
    "* 手写文字识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "6997ccce",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': [{'location': {'top': 372, 'left': 586, 'width': 1436, 'height': 616}, 'words': '倚登'}, {'location': {'top': 1102, 'left': 557, 'width': 1005, 'height': 633}, 'words': '樹'}], 'words_result_num': 2, 'log_id': 1513857160962162554}\n"
     ]
    }
   ],
   "source": [
    "## 实践-3\n",
    "\n",
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "手写文字识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('shufa.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img}\n",
    "access_token = '24.f9de814de8230b35a30dbf045fd44274.2592000.1652358632.282335-25954563'\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f58548ff",
   "metadata": {},
   "source": [
    "* 二维码识别                                         \n",
    "* 草料二维码生成器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "9e5b048c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'codes_result': [], 'codes_result_num': 0, 'log_id': 1513857570323449886}\n"
     ]
    }
   ],
   "source": [
    "## 实践-4\n",
    "\n",
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "二维码识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/qrcode\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('erweima.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img}\n",
    "access_token = '24.f9de814de8230b35a30dbf045fd44274.2592000.1652358632.282335-25954563'\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "77a39468",
   "metadata": {},
   "source": [
    "* 卡片类文字识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "20d412cd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': {'姓名': {'location': {'top': 415, 'left': 659, 'width': 345, 'height': 131}, 'words': '陈朋涛'}, '民族': {'location': {'top': 641, 'left': 1207, 'width': 77, 'height': 103}, 'words': '汉'}, '住址': {'location': {'top': 1047, 'left': 664, 'width': 862, 'height': 113}, 'words': '山东省滕州市龙阳镇'}, '公民身份号码': {'location': {'top': 1547, 'left': 1100, 'width': 1336, 'height': 164}, 'words': '532101198906010015'}, '出生': {'location': {'top': 838, 'left': 654, 'width': 858, 'height': 106}, 'words': '19890601'}, '性别': {'location': {'top': 637, 'left': 664, 'width': 85, 'height': 103}, 'words': '男'}}, 'words_result_num': 6, 'image_status': 'normal', 'idcard_number_type': 1, 'log_id': 1513859601304930009}\n"
     ]
    }
   ],
   "source": [
    "## 实践-5 身份证 \n",
    "\n",
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "身份证识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/idcard\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('shenfenzheng.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"id_card_side\":\"front\",\"image\":img}\n",
    "access_token = '24.f9de814de8230b35a30dbf045fd44274.2592000.1652358632.282335-25954563'\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "ac047eb5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result': {'valid_date': '08/23', 'bank_card_number': '623063 000001319311', 'bank_name': '福建海峡银行股份有限公司', 'bank_card_type': 1, 'holder_name': ''}, 'direction': 0, 'log_id': 1513859307626411001}\n"
     ]
    }
   ],
   "source": [
    "# 银行卡\n",
    "\n",
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "银行卡识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('yinghangka.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img}\n",
    "access_token = '24.f9de814de8230b35a30dbf045fd44274.2592000.1652358632.282335-25954563'\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fd759baf",
   "metadata": {},
   "source": [
    "* 财务类文字识别-增值税发票识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "a76e19f0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result_num': 43, 'words_result': {'AmountInWords': '', 'InvoiceNumConfirm': '28514150', 'CommodityEndDate': [], 'CommodityVehicleType': [], 'CommodityStartDate': [], 'CommodityPrice': [{'row': '1', 'word': '7'}, {'row': '2', 'word': '7'}], 'NoteDrawer': 'm', 'SellerAddress': '浦东新区毕升路289弄4号楼201室58432009', 'CommodityNum': [{'row': '1', 'word': '1'}, {'row': '2', 'word': '1'}], 'SellerRegisterNum': '310229687345127', 'MachineCode': '', 'Remarks': '', 'SellerBank': '中国农业银行上海市浦东花木支行03319900040009977', 'CommodityTaxRate': [{'row': '1', 'word': '17%'}, {'row': '2', 'word': '17%'}], 'TotalTax': '', 'InvoiceCodeConfirm': '3100113140', 'CheckCode': '', 'InvoiceCode': '3100113140', 'InvoiceDate': '2012年01月16日', 'PurchaserRegisterNum': '5002277500FF', 'InvoiceTypeOrg': '上海增值税专用发票', 'OnlinePay': '', 'Password': 'M', 'Agent': '否', 'AmountInFiguers': '', 'PurchaserBank': '甲明MM用', 'Checker': '', 'City': '', 'TotalAmount': '', 'CommodityAmount': [{'row': '1', 'word': '0.00'}, {'row': '2', 'word': '0.00'}], 'PurchaserName': '', 'CommodityType': [{'row': '1', 'word': '2.5kg'}, {'row': '2', 'word': '500g'}], 'Province': '上海', 'InvoiceType': '专用发票', 'SheetNum': '第一联：记账联', 'PurchaserAddress': '100', 'CommodityTax': [{'row': '1', 'word': '月国'}], 'CommodityPlateNum': [], 'CommodityUnit': [{'row': '1', 'word': '瓶'}, {'row': '2', 'word': '瓶'}], 'Payee': '四丹', 'CommodityName': [{'row': '1', 'word': 'N-甲基-D-葡糖胶'}, {'row': '2', 'word': '已二酸二酰耕'}], 'SellerName': '萨恩化学技术(上海)有限公司', 'InvoiceNum': '28514150'}, 'log_id': 1513862440746119871}\n"
     ]
    }
   ],
   "source": [
    "## 实践-6 \n",
    "\n",
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "增值税发票识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('zhengzhishui.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img}\n",
    "access_token = '24.f9de814de8230b35a30dbf045fd44274.2592000.1652358632.282335-25954563'\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "49d609f3",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
